<?php
declare (strict_types = 1);

namespace app\controller;

use app\model\Carouse;
use app\model\User;
use app\traits\CommonTrait;
use think\exception\ValidateException;
use think\facade\Request;
use app\validate\Carouse as CarouseValidate;

class AdminCarouse
{
    use CommonTrait;
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $currentPage = Request::get('current_page',1);
        $perPage = $this->getPerPage();
        $list = Carouse::paginate(['list_rows'=>$perPage,'page'=>$currentPage]);
        return $this->apiJson(1,'success',$list);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function save()
    {
        $id = Request::post('id',0);
        $req = [
            'img'=>Request::post('img'),
            'url'=>Request::post('url'),
            'desc'=>Request::post('desc'),
            'status'=>Request::post('status'),
        ];
        try {
            validate(CarouseValidate::class)->check($req);
        }catch (ValidateException $e){
            return $this->apiJson(-1,$e->getMessage());
        }
        if($id){
            $exist = Carouse::where(['id'=>$id])->findOrEmpty();
            if($exist->isEmpty()){
                return $this->apiJson(-1,'参数错误');
            }
            Carouse::where(['id'=>$id])->update($req);
        }else{
            Carouse::create($req);
        }
        return $this->apiJson(1,'success');
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete()
    {
        $id = Request::post('id');
        if(!$id){
            return $this->apiJson(-1,'缺少id参数');
        }
        $exist = Carouse::where(['id'=>$id])->findOrEmpty();
        if($exist->isEmpty()){
            return $this->apiJson(-1,'参数错误');
        }
        Carouse::where(['id'=>$id])->delete();
        return $this->apiJson(1,'success');
    }

    public function statusOperation()
    {
        $id = Request::post('id');
        if(!$id){
            return $this->apiJson(-1,'缺少id参数');
        }
        $carouseExist = Carouse::where(['id'=>$id])->field('id,status')
            ->findOrEmpty();
        if($carouseExist->isEmpty()){
            return $this->apiJson(-1,'记录不存在');
        }
        if($carouseExist['status'] == 1){
            $carouseExist->status = 0;
            $carouseExist->save();
        }else{
            $carouseExist->status = 1;
            $carouseExist->save();
        }
        return $this->apiJson(1,'success');
    }
}
